﻿Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Text
Imports PhDir.DAL

Namespace DAL

    Public Class SetupDb

        Private Const CreatePhoneDbFilePath = ".\TSql\PhoneDb_CreateDbIfNotExist.sql"
        Private Const CreateTableFilePath = ".\TSql\PhoneDb_CreateTables.sql"

        Friend Shared Sub InitializeDatabase()
            Dim isSuccess = False

            Debug.Assert(File.Exists(CreatePhoneDbFilePath) = True, "PhoneDb_CreateDbIfNotExist.sql does not exist")
            Debug.Assert(File.Exists(CreateTableFilePath) = True, "PhoneDb_CreateTables.sql does not  exist")

            If Not File.Exists(CreatePhoneDbFilePath) And Not File.Exists(CreateTableFilePath) Then
                Return
            End If

            Dim createPhoneDbTSql = New StringBuilder(File.ReadAllText(CreatePhoneDbFilePath).ToString())
            Dim createTableTSql = New StringBuilder(File.ReadAllText(CreateTableFilePath).ToString())

            Using dbConnection = New DbConnection(DbContext.MasterContext)
                dbConnection.CommandText = createPhoneDbTSql.ToString()
                dbConnection.ExecuteNonQuery()

                dbConnection.CommandText = createTableTSql.ToString()
                isSuccess = dbConnection.ExecuteNonQuery()
                'Debug.Assert(isSuccess = True, "Failed to create tables and stored procedure in PhoneDb")
            End Using

            Return
        End Sub 'InitializeDatabase()

    End Class

End Namespace
